package com.cxm.weilai.security.filter;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

import com.alibaba.fastjson.JSONObject;
import com.cxm.weilai.constants.FilterTypeConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

/**
 * @program: weilai-cloud
 * @description: 响应结果处理过滤器
 * @author: ChenMan
 * @create: 2019-03-27 15:56
 */
@Component
public class ResponseFilter extends ZuulFilter {

    @Value("${filter.flag}")
    private boolean flag;

    /**
     * pre：可以在请求被路由之前调用
     * route：在路由请求时候被调用
     * post：在route和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     *
     * @return String
     */
    @Override
    public String filterType() {
        return FilterTypeConstants.FILTER_TYPE_POST;
    }

    /**
     * 越小越先执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行过滤器，过滤器是否执行的开关
     * 如果有多个过滤器时，上一个过滤器返回为true,下一个过滤器需要执行，如果为false就没必要执行了
     */
    @Override
    public boolean shouldFilter() {
//    RequestContext context = getCurrentContext();
//    return StringUtils.equals(context.getRequest().getRequestURI().toString(), authUrl);
        return flag;
    }

    @Override
    public Object run() {
        try {
            RequestContext context = getCurrentContext();

            InputStream stream = context.getResponseDataStream();
            String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));

            if (StringUtils.isNotBlank(body)) {
                JSONObject jsonObject = JSONObject.parseObject(body);
                body = jsonObject.toJSONString();
            }
            context.setResponseBody(body);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
